-module(server_logic).

%% API
-export([start/0, dispose/0, runTests/3, showTests/1, runTestsAuto/0]).
-include("definitions.hrl").

-spec start() -> no_return().
start() ->
  Devices = device_manager:readDeviceListFromFile(),
  %spawn(?DB_NODE, test_storage, start, [self()]),
  spawn(test_storage, start, [self()]),
  receive
    {ok, started} ->
      addTestIfDebug(),
      io:format("added tests~n"),
      ok
  end,
  TestIds = test_storage:getAllTestIds(),
  {WxFrame, Grid} = server_ui:createWindow(Devices, TestIds),
  server_ui:eventLoop(WxFrame, Grid, Devices),
  wx:destroy().

showTests(DeviceCount) ->
  %NextPid =
  spawn_link(info_ui, start, [self(), DeviceCount])
%,  register(infoUi, NextPid)
.

-spec runTestsAuto/0 :: () -> {[{string(), integer()}], [dict:dict(integer(), integer())]}.
runTestsAuto() ->
  Numbers = lists:seq(1, ?DEVICES_LIMIT),
  Devlist = [{"DeviceN", N} || N <- Numbers],
  Tests = test_storage:getAllTestIds(),
  TestsDict = case Tests of
                [] -> error("no tests in db");
                [H | _] -> genDictTests(Numbers, H, dict:new())
              end,
  {Devlist, TestsDict}
.

-spec genDictTests/3 :: ([integer()], integer(), dict:dict(integer(), integer())) -> dict:dict(integer(), integer()).
genDictTests([], _, Acc) ->
  Acc;

genDictTests([N | Tail], Test, Acc) ->
  NewAcc = dict:append(N, Test, Acc),
  genDictTests(Tail, Test, NewAcc)
.


-spec runTests/3 :: ([{string(), integer()}], dict:dict(), pid()) -> no_return().
runTests(Devices, Tests, Pid) ->
  test_executor:start(self(), Devices, Tests),
  receive
    {ok, testsRunning} ->
      Pid ! testsRunning,
      ok;
    X -> error(X)
  end.

dispose() ->
  test_storage:stop(),
  test_executor:stop(),
  info_ui:stop()
.

%для первых тестов
addTestIfDebug() ->
  case ?DEBUG of
    true -> test_storage:insertSamples();
    false -> ok
  end.